package net.aynt.blog.action.api;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;

import net.aynt.blog.sys.Constants;
import net.aynt.blog.util.JedisUtils;
import net.aynt.core.mvc.WebContext;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

public class AddAction {
	private final static Logger logger = LoggerFactory
			.getLogger(AddAction.class);
	
	private static final String RE = "api/re";
	
	public String index(WebContext rc) throws Exception {
		try {
			String msg = rc.getParam("msg");
			if(StringUtils.isEmpty(msg)){
				rc.setRequestAttr("re", "内容不能为空");
				return RE;
			}
			JedisPool pool = JedisUtils.getPool();
			pushCookieToQueue(msg, pool);
			rc.setRequestAttr("re", "长官名利已下达");
		} catch (Exception e) {
			logger.error(e.getMessage());
			rc.setRequestAttr("re", "系统发生错误:" + e.getMessage());
		}
		return RE;
	}
	
	private void pushCookieToQueue(String type
			, JedisPool pool) throws Exception {
		String pushDtae = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
				.format(new Date());
		Jedis jedis = null;
		try{
			JSONObject json = new JSONObject();
			json.put("type", type);
			json.put("pushDate", pushDtae);
			jedis = pool.getResource();
			jedis.lpush("taobao", json.toString());//推入队列
			logger.info("-->加入队列");
		}catch(Exception e){
			pool.returnBrokenResource(jedis);
			jedis = null;
			throw new Exception(e.getMessage());
		}finally{
			if(jedis != null){
				pool.returnResource(jedis);
			}
		}
	}
	
}
